<template>
  <!-- No changes to template section -->
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

const router = useRouter();

const mapContainer = ref(null);
const mapInstance = ref(null);
const markerLayerGroup = ref(null);
const infoWindow = ref(null);
const mapIsReady = ref(false);
const currentPosition = ref([116.397428, 39.90923]);
const productMarkers = ref({});
const pendingMarkers = ref([]);

// 初始化地图
const initMap = async () => {
  if (!mapContainer.value) {
    console.error('地图容器不存在');
    return;
  }
  
  try {
    // 确保AMap已加载
    const AMap = await loadAMapScript();
    
    // 默认位置（北京）
    const defaultCenter = [116.397428, 39.90923];
    
    // 确保mapContainer依然存在
    if (!mapContainer.value) {
      console.error('地图容器已失效');
      return;
    }
    
    // 解决地图容器ID问题
    if (!mapContainer.value.id) {
      mapContainer.value.id = 'map-container-' + Date.now();
    }
    
    // 创建地图实例
    mapInstance.value = new AMap.Map(mapContainer.value, {
      zoom: 13,
      center: defaultCenter,
      viewMode: '2D',
      mapStyle: 'amap://styles/whitesmoke',
      resizeEnable: true,
      jogEnable: false,
      pitchEnable: false,
      rotateEnable: false,
      animateEnable: false,
      buildingAnimation: false,
      showBuildingBlock: false,
      forceVector: false
    });
    
    // 创建标记集合图层存储所有标记
    markerLayerGroup.value = new AMap.LayerGroup();
    
    // 创建信息窗口容器
    infoWindow.value = createInfoWindow();
    
    // 地图加载完成后进行操作
    mapInstance.value.on('complete', () => {
      console.log('地图加载完成');
      
      // 标记地图已经完全渲染
      mapIsReady.value = true;
      
      // 添加基础控件
      addMapControls();
      
      // 获取当前位置
      locateCurrentPosition();
      
      // 如果有缓存的标记请求，现在处理它们
      processPendingMarkers();
      
      // 触发地图初始化完成事件
      emit('map-ready', mapInstance.value);
    });
    
    // 添加错误处理
    mapInstance.value.on('error', (error) => {
      console.error('地图加载错误:', error);
      ElMessage.warning('地图加载出错');
    });
    
  } catch (error) {
    console.error('地图初始化失败:', error);
    ElMessage.warning('地图加载失败，请刷新页面重试');
  }
};

// 创建信息窗口
const createInfoWindow = () => {
  const AMap = window.AMap;
  return new AMap.InfoWindow({
    offset: new AMap.Pixel(0, -30),
    closeWhenClickMap: true
  });
};

// 添加地图控件
const addMapControls = () => {
  const AMap = window.AMap;
  
  // 添加工具条
  mapInstance.value.addControl(new AMap.ToolBar({
    position: 'RB'
  }));
  
  // 添加比例尺
  mapInstance.value.addControl(new AMap.Scale());
};

// 定位当前位置
const locateCurrentPosition = () => {
  try {
    const AMap = window.AMap;
    
    mapInstance.value.plugin(['AMap.Geolocation'], function() {
      const geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,
        timeout: 15000, // 增加超时时间到15秒
        buttonPosition: 'LB',
        buttonOffset: new AMap.Pixel(10, 20),
        zoomToAccuracy: false, // 避免缩放导致的视觉问题
        showButton: true,
        showMarker: true,
        markerOptions: {
          icon: new AMap.Icon({
            size: new AMap.Size(32, 32),
            imageSize: new AMap.Size(32, 32),
            image: 'https://webapi.amap.com/theme/v1.3/markers/n/loc.png'
          }),
          offset: new AMap.Pixel(-16, -16)
        }
      });
      
      mapInstance.value.addControl(geolocation);
      
      geolocation.getCurrentPosition(function(status, result) {
        if (status === 'complete' && result && result.position) {
          const position = result.position;
          
          // 验证坐标有效性
          if (!isNaN(position.lng) && !isNaN(position.lat)) {
            // 更新当前位置
            currentPosition.value = [position.lng, position.lat];
            mapInstance.value.setCenter(currentPosition.value);
          } else {
            console.warn('定位返回的坐标无效，使用默认位置');
            ElMessage.warning('定位失败，使用默认位置');
          }
        } else {
          console.warn('定位失败，使用默认位置', result);
          ElMessage.warning('定位失败，使用默认位置');
        }
      });
    });
  } catch (error) {
    console.error('定位功能初始化失败:', error);
  }
};

// 添加商品标记
const addProductMarker = (product) => {
  if (!product || !product.location) {
    console.warn('无效的商品数据，无法添加标记');
    return;
  }
  
  // 如果地图尚未完全加载，将标记添加请求存储起来
  if (!mapIsReady.value || !mapInstance.value) {
    console.warn('地图尚未渲染完成，标记将在地图加载后添加');
    pendingMarkers.value.push({...product});
    return;
  }
  
  try {
    const AMap = window.AMap;
    
    // 验证位置坐标
    const position = product.location;
    if (!Array.isArray(position) || position.length !== 2 || 
        isNaN(position[0]) || isNaN(position[1])) {
      console.warn('商品位置坐标无效');
      return;
    }
    
    // 如果该产品已有标记，先移除
    if (productMarkers.value[product.id]) {
      markerLayerGroup.value.removeLayers([productMarkers.value[product.id]]);
      delete productMarkers.value[product.id];
    }
    
    // 创建标记
    const marker = new AMap.Marker({
      position: position,
      title: product.name,
      label: {
        content: `¥${product.price}`,
        direction: 'top'
      },
      clickable: true
    });
    
    // 添加点击事件
    marker.on('click', () => {
      // 构建信息窗口内容
      const content = `
        <div class="info-window">
          <div class="info-title">${product.name}</div>
          <div class="info-price">¥${product.price}</div>
          <div class="info-desc">${product.description || '暂无描述'}</div>
          <div class="info-btn">查看详情</div>
        </div>
      `;
      
      // 打开信息窗口
      infoWindow.value.setContent(content);
      infoWindow.value.open(mapInstance.value, position);
      
      // 绑定详情按钮点击事件
      nextTick(() => {
        const detailBtn = document.querySelector('.info-btn');
        if (detailBtn) {
          detailBtn.addEventListener('click', () => {
            router.push(`/product/${product.id}`);
          });
        }
      });
    });
    
    // 将标记添加到图层组
    markerLayerGroup.value.addLayers([marker]);
    markerLayerGroup.value.setMap(mapInstance.value);
    
    // 保存标记引用，方便后续操作
    productMarkers.value[product.id] = marker;
    
  } catch (error) {
    console.error('添加商品标记失败:', error);
  }
};

// 处理等待添加的标记
const processPendingMarkers = () => {
  if (pendingMarkers.value.length > 0 && mapIsReady.value) {
    console.log(`处理 ${pendingMarkers.value.length} 个等待添加的标记`);
    
    // 复制并清空等待队列
    const markers = [...pendingMarkers.value];
    pendingMarkers.value = [];
    
    // 添加标记，使用setTimeout确保不阻塞主线程
    setTimeout(() => {
      markers.forEach(product => {
        addProductMarker(product);
      });
    }, 100);
  }
};

// 动态加载高德地图API
const loadAMapScript = () => {
  return new Promise((resolve, reject) => {
    // 如果已经加载过，直接返回成功
    if (window.AMap) {
      resolve(window.AMap);
      return;
    }

    const key = 'b801e4ff3ab164d8ef56d85cd52ec0e0'; // 使用正确的高德地图Key
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${key}&plugin=AMap.Geolocation,AMap.Geocoder,AMap.ToolBar,AMap.Scale`;
    
    // 设置加载事件
    script.onload = () => {
      console.log('高德地图API加载成功');
      if (window.AMap) {
        resolve(window.AMap);
      } else {
        reject(new Error('高德地图API加载成功但AMap对象不可用'));
      }
    };
    
    // 错误处理
    script.onerror = () => {
      console.error('高德地图API加载失败');
      reject(new Error('高德地图API加载失败'));
      // 尝试清理脚本标签
      try {
        document.head.removeChild(script);
      } catch (e) {
        console.warn('清理脚本标签失败', e);
      }
    };
    
    // 添加到文档
    document.head.appendChild(script);
  });
};

// 清除所有标记
const clearMarkers = () => {
  if (markerLayerGroup.value) {
    markerLayerGroup.value.clearLayers();
  }
  productMarkers.value = {};
};

// 重新加载地图
const reloadMap = () => {
  if (mapInstance.value) {
    mapInstance.value.destroy();
    mapInstance.value = null;
  }
  mapIsReady.value = false;
  clearMarkers();
  nextTick(() => {
    initMap();
  });
};

// 设置地图中心
const setMapCenter = (position) => {
  if (!mapInstance.value || !position || 
      !Array.isArray(position) || position.length !== 2) {
    return;
  }
  
  mapInstance.value.setCenter(position);
};

// 添加多个商品标记
const addProductMarkers = (products) => {
  if (!products || !Array.isArray(products)) {
    console.warn('无效的商品数据列表');
    return;
  }
  
  products.forEach(product => {
    addProductMarker(product);
  });
};

// 暴露给父组件的方法
defineExpose({
  initMap,
  addProductMarker,
  addProductMarkers,
  clearMarkers,
  setMapCenter,
  reloadMap
});

// 组件挂载时初始化
onMounted(() => {
  nextTick(() => {
    initMap();
  });
});
</script>

<style>
  /* No changes to style section */
</style> 